<?php defined('SYSPATH') or die('No direct script access.');

abstract class OpenLogin
{
    protected static $_login_type = '';
    private static $_instance = null;

    protected $_app_key = '';
    protected $_app_secret = '';
    protected $_callback_url = '';

    public static function instance($login_type = null)
    {
        if (null === self::$_instance)
        {
            self::$_login_type = $login_type;
            $config = Kohana::config('openlogin.'.$login_type);
            $class = 'OpenLogin_'.$login_type;
            if (!empty($config) && $config['login_switch'] && class_exists($class))
            {
                self::$_instance = new $class;
            }
            else
            {
                return null;
            }
        }
        return self::$_instance;
    }

    public static function check_state()
    {
        if (Session::instance()->get('_openlogin_state') != $_REQUEST['state']) return false;
        return true;
    }

    public static function is_login()
    {
        $uid = self::getLoginUserUid();
        return $uid > 0;
    }

    public static function getLoginUserUid ()
    {
        $uid = Session::instance()->get('uid');
        if (empty($uid))
            return 0;
        else
            return $uid;
    }

    public static function login($info)
    {
        
        $source = Arr::get($info, 'type', '');
        $userId = Arr::get($info, 'uid', '');
        $userToken = Arr::get($info, 'userToken', '');
        $userName = Arr::get($info, 'nickname', '');
        $userIcon = Arr::get($info, 'header_url', '');
        $userGender = Arr::get($info, 'gender', '');
        $utype = Arr::get($info, 'utype', '');
        $userPushId = "";
        if($userGender == '男'){
            $userGender = 'm';
        }else if($userGender == '女'){
            $userGender = 'f';
        }
        user::initUserFromBasicInfo ($source, $userId, $userToken, $userName, $userIcon, $userGender, $userPushId,$utype);
//        Session::instance()->set('uid', $user->getUserUid());
    }

    public static function logout()
    {
        Session::instance()->delete('uid');
        Session::instance()->destroy();
    }

    
    
    public function __construct()
    {
        $config = Kohana::config('openlogin.'.self::$_login_type);
        $this->_app_key     = Arr::get($config, 'app_key');
        $this->_app_secret  = Arr::get($config, 'app_secret');
        $this->_callback_url = Arr::get($config, 'callback_url');
    }

    protected function state()
    {
        $state = md5(uniqid(rand(10, 99), true));
        Session::instance()->set('_openlogin_state', $state);
        return $state;
    }

    abstract public function get_login_url();

    abstract public function get_access_token();

    abstract public function get_openid($access_token);

    abstract public function get_user_info($openid, $access_token);
}
